<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :footer="null"
    :maskClosable="false"
    switchFullscreen
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    @cancel="handleCancel"
    cancelText="关闭">

    <div>
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="入库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="beLaidUpTime">
              <j-date placeholder="请选择入库日期" v-model="model.beLaidUpTime" :show-time="true"
                      date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplierId">
              <a-select
                show-search
                placeholder="请选择供应商"
                option-filter-prop="children"
                v-model="model.supplierId"
                style="width: 100%"
                :filter-option="filterOptionSupplier"
                @focus="handleFocus"
                @blur="handleBlur"
                @change="changeSupplier">
                <a-select-option :value="item.id" v-for="(item,index) in supplierData" :key="index">
                  {{item.supplierName}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" v-if="model.relevancePurchaseOrder != null && model.relevancePurchaseOrder != '' ">
            <a-form-model-item label="关联采购单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="relevancePurchaseOrder">
              <a-input v-model="model.relevancePurchaseOrder" disabled style="width: 250px" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="采购人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchasePeople">
              <a-select
                show-search
                :allowClear="true"
                placeholder="请选择采购人员"
                option-filter-prop="children"
                v-model="model.purchasePeople"
                style="width: 100%"
                :filter-option="filterOptionPurchasePeople">
                <a-select-option :value="item.realname" v-for="(item,index) in purchasePeopleData" :key="index">
                  {{item.realname}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depositoryId">
              <a-select
                show-search
                placeholder="请选择仓库"
                option-filter-prop="children"
                v-model="model.depositoryId"
                style="width: 100%"
                :filter-option="filterOptionDepository"
                @focus="handleFocus"
                @blur="handleBlur">
                <a-select-option :value="item.id" v-for="(item,index) in depositoryData" :key="index">
                  {{item.depositoryName}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="操作" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depositoryName">
              <a-button type="primary" :loading="loading" style="margin-right: 10px" @click="submitSave(2)">提交审批</a-button>
              <a-button type="primary" @click="submitSave(1)">保存草稿</a-button>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea
                v-model="model.remark"
                placeholder="请输入备注"
                :auto-size="{ minRows: 3, maxRows: 5 }"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </div>

    <div>
      <a-button class="editable-add-btn" @click="handleAdd" style="margin-bottom: 10px" v-if="model.relevancePurchaseOrder == null || model.relevancePurchaseOrder == ''">
        添加材料
      </a-button>
      <a-button class="editable-add-btn" style="float: right" @click="saveData()">保存当前表格数据</a-button>
      <a-table
        ref="table"
        size="small"
        :scroll="scroll"
        class="j-table-force-nowrap"
        bordered
        :data-source="materialData"
        :columns="columns"
        :pagination="false"
        :rowKey="(record,index)=>{return index}"
        >

        <a slot="materialName" @click="showMaterialStock(record)" slot-scope="text,record">{{ text }}</a>

        <template v-for="col in ['unitPrice','discountRate','discountMoney','discountUnitPrice','subtotal','materialNum','remark']" :slot="col" slot-scope="text, record, index">
          <div :key="col" v-if="col !== 'discountUnitPrice' && col !== 'subtotal'">
            <a-input
              :id="col"
              style="margin: -5px 0;width: 90px;text-align: center"
              :value="text"
              @change="e => handleChange(e.target.value, record.key, col)"
            />
            <!--<template v-else>
              {{ text }}
            </template>-->
          </div>
          <div :key="col" v-if="col === 'discountUnitPrice' || col === 'subtotal'">
            <span>{{text}}</span>
          </div>
        </template>

        <template slot="operation" slot-scope="text, record, index">
          <a-popconfirm title="确定删除这条记录吗" @confirm="() => onDelete(record.key)">
            <a>删除</a>
          </a-popconfirm>
        </template>

      </a-table>

      <a-row style="margin-top: 20px">
        <a-col :span="7">
          <a-form-model-item label="合计" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseName">
            <a-input-number v-model="purchasePrice" disabled style="width: 75%"></a-input-number>
          </a-form-model-item>
        </a-col>
        <a-col :span="5">
          <a-form-model-item label="优惠率" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseName">
            <a-input-number v-model="discountedRate" style="width: 75%" @blur="changeDiscountedRate"></a-input-number>%
          </a-form-model-item>
        </a-col>
        <a-col :span="5">
          <a-form-model-item label="优惠金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseName">
            <a-input-number v-model="discountedMoney" style="width: 75%" @blur="changeDiscountedMoney"></a-input-number>
          </a-form-model-item>
        </a-col>
        <a-col :span="7">
          <a-form-model-item label="优惠后金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseName">
            <a-input-number v-model="discountedPurchasePrice" disabled style="width: 75%"></a-input-number>
          </a-form-model-item>
        </a-col>
      </a-row>
    </div>

    <choose-person-in-charge-modal ref="choosePersonInChargeModal" @selectFinished="choosePersonInChargeOk($event)"></choose-person-in-charge-modal>
    <select-material-modal ref="SelectMaterialModal" @ok="chooseMaterialOk($event)"></select-material-modal>
    <material-stock-modal ref="materialStockModal"></material-stock-modal>
  </j-modal>
</template>

<script>

  import {httpAction, getAction,deleteAction} from '@/api/manage'
  import {validateDuplicateValue} from '@/utils/util'
  import '@/assets/less/TableExpand.less'
  import choosePersonInChargeModal from "../../material/modules/choosePersonInChargeModal";
  import selectMaterialModal from "../../purchaseOrder/modules/selectMaterialModal";
  import materialStockModal from "../../purchaseOrder/modules/materialStockModal";

  export default {
    name: 'purchaseOrderModal',
    components: {
      selectMaterialModal,
      choosePersonInChargeModal,
      materialStockModal,
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },

    data() {
      return {
        scroll:{
          x:2000,
          y:400
        },
        loading: false,
        currentSupplierId: 0,   //当前选中的供应商id
        supplierData: [],
        depositoryData: [],
        materialData:[],
        cacheData: [],
        purchasePeopleData:[],
        editingKey: '',
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            },
            fixed: 'left'
          },
          {
            title: '名称',
            dataIndex: 'materialName',
            align: "center",
            ellipsis: true,
          },
          {
            title: '型号',
            dataIndex: 'modelNumber',
            align: "center",
            ellipsis: true,
          },
          {
            title: '规格',
            dataIndex: 'specifications',
            align: "center",
          },
          {
            title: '品牌',
            dataIndex: 'brand',
            align: "center",
          },
          {
            title: '单位',
            align: "center",
            dataIndex: 'unit'
          },
          {
            title: '市场价',
            dataIndex: 'marketPrice',
            align: "center",
          },
          {
            title: '预算价',
            dataIndex: 'estimatedCost',
            align: "center",
          },
          {
            title: '成本价',
            dataIndex: 'costPrice',
            align: "center",
          },
          {
            title: '单价',
            dataIndex: 'unitPrice',
            align: "center",
            scopedSlots: {customRender: 'unitPrice'},
          },
          {
            title: '数量',
            dataIndex: 'materialNum',
            align: "center",
            scopedSlots: {customRender: 'materialNum'},
          },
          {
            title: '折扣率(%)',
            dataIndex: 'discountRate',
            align: "center",
            scopedSlots: {customRender: 'discountRate'},
          },
          {
            title: '折扣额',
            dataIndex: 'discountMoney',
            align: "center",
            scopedSlots: {customRender: 'discountMoney'},
          },
          {
            title: '折后单价',
            dataIndex: 'discountUnitPrice',
            align: "center",
            scopedSlots: {customRender: 'discountUnitPrice'},
          },
          {
            title: '金额',
            dataIndex: 'subtotal',
            align: "center",
            scopedSlots: {customRender: 'subtotal'},
          },
          {
            title: '备注',
            dataIndex: 'remark',
            align: "center",
            scopedSlots: {customRender: 'remark'},
          },
          {
            title: '操作',
            dataIndex: 'operation',
            width: 80,
            fixed: 'right',
            align: "center",
            scopedSlots: {customRender: 'operation'},
          },
        ],
        title: '',
        width: '95%',
        visible: false,
        disableSubmit: false,
        fullscreen: true,
        keyIndex: 0,
        addRowBeginIndex: 0,
        model: {},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 15},
        },
        confirmLoading: false,
        validatorRules: {
          beLaidUpTime: [{ required: true, message: '入库时间不能为空' }],
          supplierId: [{ required: true, message: '请选择供应商' }],
          purchasePeople: [{ required: true, message: '请选择采购员' }],
          depositoryId: [{ required: true, message: '请选择仓库' }],
          remark: [
            { max: 100, message: '最多输入100个字符' },
          ],
        },
        selectedRowKeys: [],
        selectedRows: [],
        url: {
          add: "/ghSupplychainPurchaseOrder/add",
          edit: "/ghSupplychainPurchaseOrder/edit",
          queryById: "/ghSupplychainPurchaseOrder/queryById",
          querySupplierList: "/ghSupplychainSupplier/allList",
          queryDepositoryList: "/ghSupplychainDepository/allList",
          queryMaterialList: "/ghSupplychainMaterial/allList",
          queryInDepositoryOrderItemList: "/ghSupplychainPurchaseOrderItem/list",
          deleteInDepositoryOrderItem: "/ghSupplychainPurchaseOrderItem/delete",
          queryUserList: "/sys/user/allList",
        },
        discountedRate:0,
        discountedMoney:0,
        purchasePrice:0,
        discountedPurchasePrice:0,
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      },
    },
    created() {
      //备份model原始值
      //this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      //修改优惠率
      changeDiscountedRate(){
        if (this.discountedRate != null && this.discountedRate !== ""){
          if (parseFloat(this.discountedRate) > 100){
            this.$message.error("优惠率不能超过100%")
            this.discountedRate = 100;
          }
          if (parseFloat(this.purchasePrice) !== 0){
            let discountedMoney = parseFloat(parseFloat(this.purchasePrice) * (this.discountedRate / 100)).toFixed(2)
            let discountedPurchasePrice = this.purchasePrice - discountedMoney;
            this.discountedMoney = discountedMoney
            this.discountedPurchasePrice = discountedPurchasePrice
          }else {
            this.discountedMoney = 0;
            this.discountedPurchasePrice = 0;
          }
        }
      },
      //修改优惠金额
      changeDiscountedMoney(){
        if (this.discountedMoney != null && this.discountedMoney !== ""){
          if (parseFloat(this.discountedMoney) > parseFloat(this.purchasePrice)){
            this.$message.error("优惠金额不能超过总计")
            this.discountedMoney = this.purchasePrice;
          }
          if (parseFloat(this.purchasePrice) !== 0){
            this.discountedRate = parseFloat((this.discountedMoney / this.purchasePrice) * 100).toFixed(2);
            this.discountedPurchasePrice = this.purchasePrice - this.discountedMoney;
          }else {
            this.discountedRate = 0;
            this.discountedPurchasePrice = 0;
          }
        }
      },
      handleChange(value, key, column) {
        const newData = [...this.materialData];
        const target = newData.find(item => key === item.key);
        if (target) {
          target[column] = value;
          if (column === 'discountRate'){
            if (target.materialNum != null){
              target['discountMoney'] = (target.unitPrice * target.materialNum * (value / 100)).toFixed(2)
            }
          }else if (column === 'discountMoney'){
            if (target.materialNum != null){
              target['discountRate'] = (value / (target.unitPrice * target.materialNum) * 100).toFixed(2)
            }
          }
          if (target.unitPrice != null && target.materialNum != null){
            if (target.discountMoney != null){
              target['subtotal'] = (target.unitPrice * target.materialNum - target.discountMoney).toFixed(2);
            }else {
              target['subtotal'] = (target.unitPrice * target.materialNum).toFixed(2);
            }
          }
          this.materialData = newData;
        }
      },

      saveData(){
        const newData = [...this.materialData];
        newData.forEach(function (item) {
          delete item.editable;
        })
        this.materialData = newData;
        this.materialData.forEach(function (item) {
          delete item.editable;
          if (item.unitPrice != null && item.materialNum != null){
            if (item.discountMoney != null){
              item.subtotal = (item.unitPrice * item.materialNum - item.discountMoney).toFixed(2)
            }else {
              item.subtotal = (item.unitPrice * item.materialNum).toFixed(2)
            }
          }
          if (item.materialNum != null && item.discountMoney != null){
            item.discountRate = (item.discountMoney / (item.unitPrice * item.materialNum) * 100).toFixed(2)
          }
          if (item.discountRate != null){
            item.discountUnitPrice = (item.unitPrice - item.unitPrice * (item.discountRate/100)).toFixed(2)
          }
        })
        this.calculateSubtotal();
      },

      //计算总价
      calculateSubtotal(){
        let purchasePrice = 0;
        this.materialData.forEach(function (item) {
          if (item.subtotal != null){
            purchasePrice += parseFloat(item.subtotal);
          }
        })
        this.purchasePrice = purchasePrice.toFixed(2);
        this.discountedPurchasePrice = this.purchasePrice - this.discountedMoney;
      },

      onDelete(key) {
        let deleteKeyIndex = 0;
        if(this.model.id){
          if (key <= this.addRowBeginIndex){
            let obj=this.materialData.find(function (obj) {
              return obj.key === key;
            })
            deleteAction(this.url.deleteInDepositoryOrderItem,{id:obj.id}).then(res=>{
              if (res.success){
                this.$message.success(res.message)
              }else {
                this.$message.warning(res.message)
              }
            })
          }
        }
        const data = [...this.materialData];
        this.materialData = data.filter(item => item.key !== key);
        let purchasePrice = 0;
        this.materialData.forEach(function (item) {
          item['key'] = deleteKeyIndex;
          if (item.subtotal != null){
            purchasePrice += parseFloat(item.subtotal)
          }
          deleteKeyIndex++;
        })
        this.purchasePrice = parseFloat(purchasePrice).toFixed(2)
        this.discountedMoney = parseFloat(purchasePrice * (this.discountedRate / 100)).toFixed(2)
        this.discountedPurchasePrice = parseFloat(purchasePrice - this.discountedMoney).toFixed(2)
        this.keyIndex = deleteKeyIndex;
      },
      //查询库存并显示
      showMaterialStock(record){
        this.$refs.materialStockModal.title = "库存详情";
        this.$refs.materialStockModal.showMaterialStock(record);
      },
      //加载用户列表
      loadUserListData() {
        getAction(this.url.queryUserList).then((res) => {
          if (res.success) {
            this.purchasePeopleData = res.result.records||res.result;
          }
        })
      },
      //加载供应商
      loadSupplierData(){
        getAction(this.url.querySupplierList).then((res) => {
          if (res.success) {
            this.supplierData = res.result.records||res.result;
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      //加载仓库
      loadDepositoryData(){
        getAction(this.url.queryDepositoryList).then((res) => {
          if (res.success) {
            this.depositoryData = res.result.records||res.result;
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      changeSupplier(value) {
        this.currentSupplierId = value;
        this.materialData = [];
        this.cacheData = [];
      },
      handleBlur() {
        console.log('blur');
      },
      handleFocus() {
        console.log('focus');
      },
      filterOptionSupplier(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      filterOptionPurchasePeople(input, option){
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      filterOptionDepository(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      handleAdd() {
        if (this.currentSupplierId == 0 || this.currentSupplierId == null){
          this.$message.warning("请先选择供应商")
          return;
        }
        this.$refs.SelectMaterialModal.title = "请选择材料";
        this.$refs.SelectMaterialModal.add(this.currentSupplierId);
      },

      chooseMaterialOk(arr){
        //去重
        let newArr = Array.from(new Set(arr));
        for (let i=0;i<newArr.length;i++){
          newArr[i].key = this.keyIndex;
          newArr[i].materialId = newArr[i].id;
          newArr[i].id = null;
          newArr[i].unitPrice = newArr[i].costPrice;
          this.materialData.push(newArr[i]);
          this.cacheData.push(newArr[i]);
          this.keyIndex++;
        }
        //todo
      },
      addInDepositoryOrder() {
        this.visible = true;
      },
      editInDepositoryOrder(record) {
        this.model = Object.assign({}, record);
        this.currentSupplierId = record.supplierId;

        this.purchasePrice = this.model.purchasePrice
        this.discountedRate = this.model.discountedRate
        this.discountedMoney = this.model.discountedMoney
        this.discountedPurchasePrice = this.model.discountedPurchasePrice

        getAction(this.url.queryInDepositoryOrderItemList, {id:record.id}).then((res) => {
          if (res.success) {
            let total = 0;
            this.materialData = res.result.records||res.result;
            for (let i=0;i<this.materialData.length;i++){
              this.materialData[i].key = i.toString();
              this.cacheData.push(this.materialData[i]);
              total += this.materialData[i].subtotal;
            }
            if (this.model.relevancePurchaseOrder != null && this.model.relevancePurchaseOrder != ""){
              this.purchasePrice = total;
              if (this.discountedMoney != null){
                this.discountedPurchasePrice = this.purchasePrice - this.discountedMoney;
              }else{
                this.purchasePrice = total;
              }
            }
            this.keyIndex = this.materialData.length;
            this.addRowBeginIndex = this.materialData[this.materialData.length-1].key;
          }else{
            this.$message.warning(res.message)
          }
        })
        this.visible = true;
      },
      //提交审批，保存草稿
      submitSave(status){
        const that = this;
        let httpurl = '';
        let method = '';
        this.loading = true;
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.materialData.length == 0){
              this.loading = false;
              this.$message.warning("请至少添加一条有效数据")
              return;
            }else {
              if (!this.model.id) {
                httpurl += this.url.add;
                method = 'post';
              } else {
                httpurl += this.url.edit;
                method = 'put';
              }
            }
            let total = 0;
            for (let i=0;i<this.materialData.length;i++){
              if (this.materialData[i].materialNum == null || this.materialData[i].materialNum == 0){
                this.loading = false;
                this.$message.warning("请输入【"+this.materialData[i].materialName+"】材料的数量")
                return;
              }else {
                if (this.materialData[i].materialNum < 0){
                  this.loading = false;
                  this.$message.warning("【"+this.materialData[i].materialName+"】材料的数量输入有误")
                  return;
                }
                if (this.materialData[i].notWarehousedNum != null && this.materialData[i].materialNum > this.materialData[i].notWarehousedNum){
                  this.loading = false;
                  this.$message.error("【"+this.materialData[i].materialName+"】材料的入库数量大于待入库数量！")
                  //this.materialData[i].materialNum = this.materialData[i].receivedNum;
                  return;
                }
              }
              if (this.materialData[i].unitPrice == null){
                this.loading = false;
                this.$message.warning("请输入【"+this.materialData[i].materialName+"】材料的单价")
                return;
              }else {
                if (this.materialData[i].unitPrice < 0){
                  this.loading = false;
                  this.$message.warning("【"+this.materialData[i].materialName+"】材料的单价输入有误")
                  return;
                }
              }
              //total += this.materialData[i].unitPrice * this.materialData[i].materialNum;
            }
            this.model.materialPurchaseOrderItemVos = this.materialData;
            //this.model.purchasePrice = total;
            this.model.purchasePrice = this.purchasePrice
            this.model.discountedRate = this.discountedRate
            this.model.discountedMoney = this.discountedMoney
            this.model.discountedPurchasePrice = this.discountedPurchasePrice;
            this.model.orderStatus = status;
            this.model.receiptsType = 2;
            httpAction(httpurl, this.model, method).then((res) => {
              if (res.success) {
                that.loading = false;
                that.$message.success(res.message);
                that.$emit('ok');
                that.close();
              } else {
                that.loading = false;
                that.$message.error(res.message);
              }
            })
          }
        })
      },
      onClearSelected() {
        this.selectedRowKeys = [];
        this.selectionRows = [];
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectionRows
      },
      close() {
        this.$emit('close');
        this.visible = false;
        this.onClearSelected();
        this.currentSupplierId = 0;
        this.materialData = [];
        this.cacheData = [];
        this.model = {};
        this.keyIndex = 0;
        this.currentChoosePersonInCharge = "";
        this.editingKey = '';
      },
      handleCancel() {
        this.close()
      },

    }
  }
</script>
<style scoped>
  .editable-row-operations a {
    margin-right: 8px;
  }
  .tableHiddle {
    display: none;
  }
</style>